package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Service.VeImageXUploadService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 火山引擎 veImageX 控制器
 * 提供图片上传相关的REST API接口
 */
@RestController
@RequestMapping("/veimagex")
@CrossOrigin(origins = "*")
public class VeImageXController {

    private static final Logger logger = LoggerFactory.getLogger(VeImageXController.class);

    @Autowired
    private VeImageXUploadService veImageXUploadService;

    /**
     * 上传图片文件
     * @param file 图片文件
     * @param fileName 文件名（可选）
     * @return 上传结果
     */
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<Map<String, Object>>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileName", required = false) String fileName) {

        logger.info("接收到图片上传请求，文件名: {}", file.getOriginalFilename());

        Map<String, Object> response = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(ApiResponse.error("文件不能为空"));
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                response.put("success", false);
                response.put("message", "只支持图片文件");
                return ResponseEntity.badRequest().body(ApiResponse.error("只支持图片文件"));
            }

            // 调用上传服务
            Map<String, Object> result = veImageXUploadService.uploadImage(file, fileName);
            return ResponseEntity.ok(ApiResponse.success(result));

        } catch (Exception e) {
            logger.error("图片上传异常", e);
            response.put("success", false);
            response.put("message", "上传异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(ApiResponse.error("图片上传异常"));
        }
    }

    /**
     * 获取上传凭证
     * 用于客户端直传
     * @return 上传凭证信息
     */
    @GetMapping("/upload-auth")
    public ResponseEntity<Map<String, Object>> getUploadAuth() {
        logger.info("获取上传凭证请求");

        try {
            Map<String, Object> result = veImageXUploadService.getUploadAuth();
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("获取上传凭证异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取上传凭证异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除图片
     * @param imageUri 图片URI
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteImage(@RequestParam("imageUri") String imageUri) {
        logger.info("删除图片请求，URI: {}", imageUri);

        Map<String, Object> response = new HashMap<>();

        try {
            boolean success = veImageXUploadService.deleteImage(imageUri);
            response.put("success", success);
            response.put("message", success ? "删除成功" : "删除失败");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("删除图片异常", e);
            response.put("success", false);
            response.put("message", "删除异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取图片信息
     * @param imageUri 图片URI
     * @return 图片信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getImageInfo(@RequestParam("imageUri") String imageUri) {
        logger.info("获取图片信息请求，URI: {}", imageUri);

        try {
            Map<String, Object> result = veImageXUploadService.getImageInfo(imageUri);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("获取图片信息异常", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取图片信息异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 健康检查接口
     * 验证veImageX模块是否正常工作
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> response = new HashMap<>();

        try {
            // 简单的健康检查，验证服务是否可用
            response.put("success", true);
            response.put("message", "veImageX模块运行正常");
            response.put("timestamp", System.currentTimeMillis());

            logger.info("veImageX健康检查通过");
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("veImageX健康检查失败", e);
            response.put("success", false);
            response.put("message", "veImageX模块异常: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}